
package cup.modules.visual.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cup.core.mp.base.BaseServiceImpl;
import cup.modules.visual.dto.VisualDTO;
import lombok.AllArgsConstructor;
import cup.modules.visual.entity.Visual;
import cup.modules.visual.entity.VisualConfig;
import cup.modules.visual.mapper.VisualMapper;
import cup.modules.visual.service.IVisualConfigService;
import cup.modules.visual.service.IVisualService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 可视化表 服务实现类
 *
 *
 */
@Service
@AllArgsConstructor
public class VisualServiceImpl extends BaseServiceImpl<VisualMapper, Visual> implements IVisualService {

	private final IVisualConfigService configService;

	@Override
	public VisualDTO detail(Long id) {
		Visual visual = this.getById(id);
		VisualConfig visualConfig = configService.getOne(Wrappers.<VisualConfig>query().lambda().eq(VisualConfig::getVisualId, id));
		VisualDTO dto = new VisualDTO();
		dto.setVisual(visual);
		dto.setConfig(visualConfig);
		return dto;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveVisual(VisualDTO dto) {
		Visual visual = dto.getVisual();
		VisualConfig visualConfig = dto.getConfig();
		boolean tempV = this.save(visual);
		visualConfig.setVisualId(visual.getId());
		boolean tempVc = configService.save(visualConfig);
		return tempV && tempVc;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateVisual(VisualDTO dto) {
		Visual visual = dto.getVisual();
		VisualConfig visualConfig = dto.getConfig();
		if (visual != null && visual.getId() != null) {
			this.updateById(visual);
		}
		if (visualConfig != null && visualConfig.getId() != null) {
			configService.updateById(visualConfig);
		}
		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Long copyVisual(Long id) {
		Visual visual = this.getById(id);
		VisualConfig visualConfig = configService.getOne(Wrappers.<VisualConfig>query().lambda().eq(VisualConfig::getVisualId, id));
		if (visual != null && visualConfig != null) {
			visual.setId(null);
			visual.setCopyFrom(String.valueOf(id));
			String copyName =generateCopyName(id,visual.getTitle());
			visual.setTitle(copyName);
			visualConfig.setId(null);
			VisualDTO dto = new VisualDTO();
			dto.setVisual(visual);
			dto.setConfig(visualConfig);
			boolean temp = this.saveVisual(dto);
			if (temp) {
				return visual.getId();
			}
		}
		return null;
	}

	private String generateCopyName(Long id, String title) {
		StringBuilder sb = new StringBuilder();
		int count = this.count(Wrappers.<Visual>lambdaQuery().eq(Visual::getCopyFrom, String.valueOf(id)));
		sb.append(title).append(" _copy(").append(++count).append(")");
		return sb.toString();
	}
}
